package com.aiassistant.controller;

import com.aiassistant.components.ToggleSwitch;
import com.aiassistant.model.Settings;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.Parent;
import javafx.scene.Node;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * 设置控制器类
 */
public class SettingsController implements Initializable {

    @FXML
    private BorderPane settingsPane;
    
    @FXML
    private ComboBox<String> fontSizeComboBox;
    
    @FXML
    private ComboBox<String> apiModelComboBox;
    
    @FXML
    private PasswordField apiKeyField;
    
    @FXML
    private TextField apiUrlField;
    
    @FXML
    private Button apiKeyVisibilityButton;
    
    @FXML
    private Button testApiButton;
    
    @FXML
    private Button resetButton;
    
    @FXML
    private Button saveButton;
    
    @FXML
    private Label versionLabel;
    
    @FXML
    private ToggleSwitch darkModeToggle;
    
    @FXML
    private ToggleSwitch autoReplyToggle;
    
    @FXML
    private ToggleSwitch soundNotificationToggle;
    
    private Label linkLabel;
    
    private Settings settings;
    private boolean isPasswordVisible = false;
    private TextField apiKeyTextField;
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        settings = Settings.getInstance();
        
        // 初始化组件
        initializeComboBoxes();
        initializeToggleSwitches();
        initializeFields();
        initializeButtons();
        
        // 设置版本信息
        if (versionLabel != null) {
            versionLabel.setText("版本: " + settings.getAppVersion());
        }
        
        // 找到链接标签并添加点击事件
        Node linkLabelNode = findLinkLabel(settingsPane);
        if (linkLabelNode instanceof Label) {
            linkLabel = (Label) linkLabelNode;
            linkLabel.setOnMouseClicked(event -> openApiKeyHelp());
        }
        
        // 应用当前主题设置
        updateTheme(settings.isDarkMode());
    }
    
    /**
     * 初始化下拉列表
     */
    private void initializeComboBoxes() {
        // 字体大小选项
        fontSizeComboBox.getItems().addAll("小", "中", "大");
        fontSizeComboBox.setValue(settings.getFontSize());
        
        // API模型选项
        apiModelComboBox.getItems().addAll("GPT-3.5", "GPT-4", "文心一言", "通义千问", "自定义");
        apiModelComboBox.setValue(settings.getApiModel());
    }
    
    /**
     * 初始化开关组件
     */
    private void initializeToggleSwitches() {
        darkModeToggle.setSelected(settings.isDarkMode());
        autoReplyToggle.setSelected(settings.isAutoReply());
        soundNotificationToggle.setSelected(settings.isSoundNotification());
        
        // 添加监听器，实现暗黑模式切换
        darkModeToggle.selectedProperty().addListener((observable, oldValue, newValue) -> {
            settings.setDarkMode(newValue);
            updateTheme(newValue);
        });
    }
    
    /**
     * 打开API密钥帮助页面
     */
    private void openApiKeyHelp() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("获取API密钥");
        alert.setHeaderText("如何获取OpenAI API密钥");
        alert.setContentText("1. 登录或注册OpenAI账号\n2. 访问API密钥页面: https://platform.openai.com/account/api-keys\n3. 点击\"Create new secret key\"按钮\n4. 复制生成的密钥并粘贴到此处\n\n注意: 请妥善保管您的API密钥，不要泄露给他人。");
        alert.showAndWait();
    }
    
    /**
     * 更新主题
     */
    private void updateTheme(boolean isDarkMode) {
        if (isDarkMode) {
            settingsPane.getStyleClass().add("dark-mode");
        } else {
            settingsPane.getStyleClass().remove("dark-mode");
        }
    }
    
    /**
     * 初始化输入字段
     */
    private void initializeFields() {
        apiKeyField.setText(settings.getApiKey());
        apiUrlField.setText(settings.getApiUrl());
        
        // 创建用于显示密钥的TextField（初始不可见）
        apiKeyTextField = new TextField(settings.getApiKey());
        apiKeyTextField.setVisible(false);
        apiKeyTextField.setManaged(false);
        
        // 延迟添加TextField，确保父容器已经完全初始化
        Platform.runLater(() -> {
            // 将TextField添加到密钥字段所在的HBox容器中
            Node passwordFieldParent = apiKeyField.getParent();
            if (passwordFieldParent instanceof HBox) {
                HBox container = (HBox) passwordFieldParent;
                // 确保在PasswordField的相同位置添加TextField
                int index = container.getChildren().indexOf(apiKeyField);
                if (index >= 0) {
                    container.getChildren().add(index, apiKeyTextField);
                    // 设置相同的增长属性
                    HBox.setHgrow(apiKeyTextField, HBox.getHgrow(apiKeyField));
                }
            } else {
                System.err.println("无法找到API密钥字段的HBox父容器");
            }
        });
    }
    
    /**
     * 初始化按钮事件
     */
    private void initializeButtons() {
        // API密钥显示/隐藏切换
        apiKeyVisibilityButton.setOnAction(event -> toggleApiKeyVisibility());
        
        // 测试API连接
        testApiButton.setOnAction(event -> testApiConnection());
        
        // 重置设置
        resetButton.setOnAction(event -> resetSettings());
        
        // 保存设置
        saveButton.setOnAction(event -> saveSettings());
    }
    
    /**
     * 切换API密钥显示/隐藏状态
     */
    private void toggleApiKeyVisibility() {
        isPasswordVisible = !isPasswordVisible;
        
        if (isPasswordVisible) {
            apiKeyVisibilityButton.setText("隐藏");
            apiKeyTextField.setText(apiKeyField.getText());
            apiKeyTextField.setVisible(true);
            apiKeyTextField.setManaged(true);
            apiKeyField.setVisible(false);
            apiKeyField.setManaged(false);
        } else {
            apiKeyVisibilityButton.setText("显示");
            apiKeyField.setText(apiKeyTextField.getText());
            apiKeyField.setVisible(true);
            apiKeyField.setManaged(true);
            apiKeyTextField.setVisible(false);
            apiKeyTextField.setManaged(false);
        }
    }
    
    /**
     * 测试API连接
     */
    private void testApiConnection() {
        String apiUrl = apiUrlField.getText();
        String apiKey = isPasswordVisible ? apiKeyTextField.getText() : apiKeyField.getText();
        String apiModel = apiModelComboBox.getValue();
        
        // 创建进度指示器
        ProgressIndicator progressIndicator = new ProgressIndicator();
        progressIndicator.setPrefSize(20, 20);
        
        // 在进行实际测试前先检查输入是否有效
        if (apiKey == null || apiKey.trim().isEmpty()) {
            showAlert(Alert.AlertType.WARNING, "API密钥为空", "请输入有效的API密钥以进行测试。");
            return;
        }
        
        // 这里执行API连接测试
        // 实际项目中应该调用API服务进行测试
        showAlert(Alert.AlertType.INFORMATION, "API连接测试", "测试成功！已成功连接到 " + apiModel + " API。");
    }
    
    /**
     * 显示警告框
     */
    private void showAlert(Alert.AlertType alertType, String title, String content) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
    
    /**
     * 重置设置为默认值
     */
    private void resetSettings() {
        Alert confirmAlert = new Alert(Alert.AlertType.CONFIRMATION);
        confirmAlert.setTitle("确认重置");
        confirmAlert.setHeaderText(null);
        confirmAlert.setContentText("确定要将所有设置恢复为默认值吗？");
        
        if (confirmAlert.showAndWait().get() == ButtonType.OK) {
            settings.resetToDefaults();
            
            // 更新UI显示
            fontSizeComboBox.setValue(settings.getFontSize());
            apiModelComboBox.setValue(settings.getApiModel());
            apiKeyField.setText(settings.getApiKey());
            apiUrlField.setText(settings.getApiUrl());
            
            // 更新开关状态
            darkModeToggle.setSelected(settings.isDarkMode());
            autoReplyToggle.setSelected(settings.isAutoReply());
            soundNotificationToggle.setSelected(settings.isSoundNotification());
            
            // 重新应用主题
            updateTheme(settings.isDarkMode());
            
            // 提示用户
            showAlert(Alert.AlertType.INFORMATION, "重置完成", "所有设置已恢复为默认值。");
        }
    }
    
    /**
     * 保存设置
     */
    private void saveSettings() {
        // 保存设置
        settings.setFontSize(fontSizeComboBox.getValue());
        settings.setApiModel(apiModelComboBox.getValue());
        settings.setApiKey(isPasswordVisible ? apiKeyTextField.getText() : apiKeyField.getText());
        settings.setApiUrl(apiUrlField.getText());
        
        // 保存开关状态
        settings.setDarkMode(darkModeToggle.isSelected());
        settings.setAutoReply(autoReplyToggle.isSelected());
        settings.setSoundNotification(soundNotificationToggle.isSelected());
        
        // 保存并应用设置
        settings.saveSettings();
        
        // 提示用户
        showAlert(Alert.AlertType.INFORMATION, "保存成功", "设置已成功保存。");
    }
    
    /**
     * 在容器中查找链接标签
     */
    private Node findLinkLabel(Parent parent) {
        for (Node node : parent.getChildrenUnmodifiable()) {
            if (node instanceof Label && ((Label) node).getText().equals("点击查看获取密钥")) {
                return node;
            } else if (node instanceof Parent) {
                Node result = findLinkLabel((Parent) node);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }
} 